//
//  ShareSMS.swift
//  BMWShareSDK
//
//  Created by Li Shengbing, (Shengbing.Li@partner.bmw.com) on 2019/8/12.
//  Copyright © 2019年 Li Shengbing, (Shengbing.Li@partner.bmw.com). All rights reserved.
//

import UIKit
import MessageUI

class ShareSMS: NSObject {

    public static let shareInstance: ShareSMS = ShareSMS()
    override init() {
        super.init()
    }
    
    func share(_ body: String) {
        //UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
        if MFMessageComposeViewController.canSendText() {
            let messageViewController = MFMessageComposeViewController()
            messageViewController.body = body
            messageViewController.messageComposeDelegate = self
            BMWShareManager.topViewController()?.present(messageViewController, animated: true, completion: nil)
        }else {
           let leftTitle = BMWNSLocalizedString.localizedString("BMWSHARESDK_PLATFORM_URLSCHEME_BUTTON_TITLE", comment: "OK")
           let mainTitle = BMWNSLocalizedString.localizedString("SHARESMS_ALERT_TITLE", comment: "OK")
           BMWShareManager.topViewController()?.showAlertViewController(leftHandler: nil, rightHandler: nil, mainTitle: mainTitle, message: nil, leftTitle: leftTitle, rightTitle: nil)
        }
    }
    
}

extension ShareSMS: MFMessageComposeViewControllerDelegate {
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        //UIBarButtonItem.appearance().setTitleTextAttributes(nil, for: .normal)
        BMWShareManager.topViewController()?.dismiss(animated: true, completion: nil)
        if BMWShareManager.shareComplete != nil {
            BMWShareManager.shareComplete!(result.description)
        }
    }
}

extension MessageComposeResult {
    var description: String {
        switch self {
        case .sent:
            return BMWNSLocalizedString.localizedString("SHARE_SMS_CALLBACK_SENTSUCCESS", comment: "Sent")
        case .cancelled:
            return BMWNSLocalizedString.localizedString("SHARE_SMS_CALLBACK_CANCELLED", comment: "Cancelled")
        case .failed:
            return BMWNSLocalizedString.localizedString("SHARE_SMS_CALLBACK_SENTFAIL", comment: "Failed to send message")
        }
    }
}
